"use client"

import { useEffect, useState } from "react"
import { generateNickname } from "@/utils/nickname"
import { generateAvatar } from "@/utils/avatar"

export type User = {
  id: string
  nickname: string
  avatarSeed: string
  avatarUrl: string
}

export function useUser() {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // Check if user exists in local storage
    const checkAndCreateUser = async () => {
      try {
        const storedUser = localStorage.getItem("chatUser")

        if (storedUser) {
          const parsedUser = JSON.parse(storedUser)
          setUser({
            ...parsedUser,
            avatarUrl: generateAvatar(parsedUser.avatarSeed),
          })

          // Update the user's last seen timestamp
          updateUserLastSeen(parsedUser.id).catch(console.error)
        } else {
          // Create a new anonymous user
          await createAnonymousUser()
        }
      } catch (error) {
        console.error("Error in user management:", error)
        // Fallback to create a new user if there's an error
        await createAnonymousUser()
      } finally {
        setLoading(false)
      }
    }

    checkAndCreateUser()

    // Set up an interval to update the user's last seen timestamp
    const interval = setInterval(() => {
      if (user?.id) {
        updateUserLastSeen(user.id).catch(console.error)
      }
    }, 60000) // Every minute

    return () => clearInterval(interval)
  }, [user?.id])

  const createAnonymousUser = async () => {
    setLoading(true)

    try {
      // Generate random nickname and avatar seed
      const nickname = generateNickname()
      const avatarSeed = Math.random().toString(36).substring(2, 10)

      console.log("Creating new user with:", { nickname, avatarSeed })

      // Insert the new user into the database
      const response = await fetch("/api/users", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ nickname, avatarSeed }),
      })

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        console.error("Server response:", response.status, errorData)
        throw new Error(`Failed to create user: ${response.status}`)
      }

      const data = await response.json()

      if (!data.user) {
        console.error("Invalid response format:", data)
        throw new Error("Invalid server response")
      }

      console.log("User created successfully:", data.user)

      // Create the user object
      const newUser = {
        id: data.user.id,
        nickname: data.user.nickname,
        avatarSeed: data.user.avatar_seed,
        avatarUrl: generateAvatar(data.user.avatar_seed),
      }

      // Save to local storage
      localStorage.setItem("chatUser", JSON.stringify(newUser))

      setUser(newUser)
    } catch (error) {
      console.error("Error creating anonymous user:", error)

      // Create a fallback user that works offline
      const fallbackUser = createFallbackUser()
      setUser(fallbackUser)
    } finally {
      setLoading(false)
    }
  }

  const createFallbackUser = () => {
    // Create a user that works offline
    const nickname = generateNickname()
    const avatarSeed = Math.random().toString(36).substring(2, 10)
    const id = `local-${Date.now()}`

    const fallbackUser = {
      id,
      nickname,
      avatarSeed,
      avatarUrl: generateAvatar(avatarSeed),
    }

    // Save to local storage
    localStorage.setItem("chatUser", JSON.stringify(fallbackUser))

    return fallbackUser
  }

  const updateUserLastSeen = async (userId: string) => {
    try {
      const response = await fetch("/api/users", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ userId }),
      })

      if (!response.ok) {
        console.warn("Failed to update user last seen:", response.status)
      }
    } catch (error) {
      console.error("Error updating user last seen:", error)
    }
  }

  return { user, loading }
}
